const { exec } = require("child_process");
const fs = require("fs");
const path = require("path");
const os = require("os");
const readSetting = require("../../lib/read_setting");
const CMD = require("../../lib/slice_video");
const SliceType = ['m3u8'];

module.exports = (req, res) => {

    let { findPath, oldname, newname, outputPath, currentIndex, duration = 5, slice_type, isCrypto = false, keyFileName } = req.body;

    if (!/^\w+$/.test(newname)) return res.send({ code: 400, msg: "未填写切片名称", result: '', ...req.body });

    if (/^\d+$/.test(duration) && duration <= 0) {
        return res.send({ code: 400, msg: "切片时长只能是数字，且必须大于0", result: '', ...req.body });
    }

    if (!SliceType.includes(slice_type)) return res.send({ code: 400, msg: "切片类型不合法", result: '', ...req.body });

    if (/^true$/.test(isCrypto)) {
        if (!/^.+\.keyinfo$/.test(keyFileName)) {
            return res.send({ code: 400, msg: "keyinfo文件名格式错误", result: '', ...req.body });
        }
    } else {
        keyFileName = false;
    }


    outputPath = outputPath || readSetting().output_path || path.join(os.homedir(), 'Desktop');

    if (!fs.existsSync(outputPath)) {
        try {
            fs.mkdirSync(outputPath, { recursive: true });
        } catch (error) {
            return res.send({ code: 400, msg: "输出路径错误！", result: '', ...req.body });
        }
    }

    // 切片文件保存的位置
    let tempPath = path.join(outputPath, `${newname}${Math.random() * 1000 | 0}`);

    if (!fs.existsSync(tempPath)) outputPath = tempPath;

    if (!findPath.trim()) return res.send({ code: 400, msg: "检索路径不存在", result: '', ...req.body });

    if (!/\.(mp4|ts)$/.test(oldname)) return res.send({ code: 400, msg: "只有 .mp4 或 .ts 格式的视频才可以切片", result: '', ...req.body });


    newname = `${newname}%05d.ts`;

    // 要转换切片的文件
    let filepath = path.resolve(findPath, oldname);

    if (!fs.existsSync(filepath)) {
        return res.send({ code: 400, msg: `路径 ${filepath} 不存在！`, result: '', ...req.body });
    }

    new Promise((resolve, reject) => {

        let savePath = path.resolve(outputPath, newname);
        let indexFile = path.resolve(outputPath, "index.m3u8");

        if (fs.existsSync(savePath)) {
            return reject("目标目录下存在同名文件！！！")
        };

        // 创建切片文件存放的目录
        fs.mkdirSync(outputPath, { recursive: true });

        let cmd = CMD(filepath, savePath, duration, indexFile, keyFileName);
        
        // return;
        exec(cmd, (err, stdout, stderr) => {
            if (err) return reject(err);
            resolve({ savePath, newname });
        })

    }).then(({ savePath, newname }) => {
        exec(`explorer "${outputPath}"`, (err, stdout, stderr) => {
            if (err) console.log(err);
        })
        res.send({
            code: 200,
            state: true,
            currentIndex,
            filename: newname,
            result: savePath,
            msg: `${newname} 分片成功！`
        })
    }).catch(err => {
        console.log(err);
        let errObj = {
            code: 500,
            state: false,
            currentIndex,
            filename: newname,
            result: err,
            msg: `${newname} 分片失败！`
        };
        res.send(errObj);
    })
}